package com.foreknow.controller;

import com.foreknow.model.Gusetbook;
import com.foreknow.service.impl.GusetbookeServiceInpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "AddMessageServlet")
public class AddMessageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        //获取到请求参数
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String content = request.getParameter("content");
        String title = request.getParameter("title");
        //调用方法
        GusetbookeServiceInpl gusetbookeServiceInpl = new GusetbookeServiceInpl();
        //newGusetbook实体类对象
        Gusetbook gusetbook = new Gusetbook();
        //然后把页面中获取到的值传进guestbook对象
        gusetbook.setName(name);
        gusetbook.setPhone(phone);
        gusetbook.setEmail(email);
        gusetbook.setContent(content);
        gusetbook.setTitle(title);
        //因为日期的类型是Java.util格式,所以用DATE下的方法转换成字符串在添加
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        gusetbook.setCreatedtime(sdf.format(new Date()));
        //调用添加对象信息的方法 返回值为boolean类型的save
        boolean save = gusetbookeServiceInpl.save(gusetbook);
        //判断如果save为TRUE的话 可以切换到GetMesagerServlet,这里有两种方法
        if (save){
//            out.println("<a href='/webDemomvc_war_exploded/getmessage'>查看所有的留言信息</a>");
            //请求转发
//            request.getRequestDispatcher("/getmessage").forward(request,response);
            //重定向
            response.sendRedirect(request.getContextPath()+"/getmessage");
        }else{
            out.println("default");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request,response);
    }
}
